//
//  ShopCarViewController.m
//  EasyToTesco2.0
//
//  Created by 杨森 on 16/5/30.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "ShopCarViewController.h"
#import "homeCollectionViewCell.h"
#import "ShopCarLastView.h"
#import "ShopCarHeaderView.h"
#import "ProductInfo.h"
#import "ShopCarTableViewCell.h"
#import "CarConfirmOrderController.h"
#import "LogInViewController.h"
#import "RecommendedController.h"

#import "GoodListsModel.h"
#import "ShopDetailsController.h"
#import "RecordPhoneType.h"
#import "ShoperCarHeaderView.h"
#import "Product.h"
#define MAR_WIDTH 5

static NSString *const reuseIdentifier = @"shopCarTableViewCell";

static NSString * const CarlikeReuseIdentifier =  @"CarlikeReuseIdentifier";

static NSString *const _isSellerSelected = @"isSellerSelected";
@interface ShopCarViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,ShopCarHeaderViewDelegate,UITableViewDataSource,UITableViewDelegate,didClickDeleteButtonDelegate,didClickShopCarHeaderViewOrButton>
{
    MBProgressHUD *progressHUD;
    
    //全选按钮
    UIButton *selectAll;
    
    //是否全选
    BOOL isSelect;
    
    //商铺
    BOOL isSellerSelected;
    
    //商铺点击indexPath
    NSInteger _sellerIndexPath;
    
    //已选的商品集合
    
    UILabel *priceLabel;
    
    UIButton *leftButton;
    
    NSMutableArray *numbersArray;
    
    NSDictionary *_urlDict;
    
    double _totlePrice;
    
    BOOL _judgeLastView;
    
    NSString *_allProductCount;
    
    //分页
    NSUInteger refreshIndex;
    
    NSInteger _pageIndex;
    
    BOOL _judgeOnceAdd;
    
    BOOL boola;
}

@property (nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,strong)NSMutableArray *productsArray;

@property (nonatomic,strong)UITableView *shopCarTableView;

@property (nonatomic,strong)ShopCarLastView *lastView;

@property (nonatomic,strong)NSMutableArray *selectedButton;

@property (nonatomic,strong) NSMutableArray *selectGoods;

/**
 所有数据数组
 */
@property (nonatomic,strong) NSMutableArray *allProductArray;

/**
 *  猜你喜欢
 */
@property(nonatomic,strong)NSMutableArray *goodsListArray;


/**
 商铺leftButton数组
 */
@property (nonatomic,strong)NSMutableDictionary *SellerLeftButtonDiction;

@property (nonatomic,strong)NSMutableArray *sellerLeftButton;

@property (nonatomic,strong)UIButton *rightButton;

@end

@implementation ShopCarViewController

static NSString * const firstReuseIdentifier =  @"firstCollectionView";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = BACKGROUND_COLOR;
    self.title = @"购物车";
    self.edgesForExtendedLayout = UIRectEdgeNone;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //    static dispatch_once_t onceToken;
    //    dispatch_once(&onceToken, ^{
    [self showHudInView:self.view hint:@"正在加载中"];
    _pageIndex = 1;
    boola = YES;
    _judgeLastView = YES;
    _judgeOnceAdd = YES;
    [self shopCartDatasources];
    
    
    
}

- (void)dealloc {
    NSLog(@"%s",__func__);
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSLog(@"%s",__func__);
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[self HUD] removeFromSuperViewOnHide];
    [self.allProductArray removeAllObjects];
    [self.shopCarTableView removeFromSuperview];
    [self.lastView removeFromSuperview];
    [self.collectionView removeFromSuperview];
    [self.shopCarTableView removeFromSuperview];
    [self.collectionView removeFromSuperview];
}

#pragma mark 数据请求
//上拉刷新
- (void)addPullUpdateData
{
    self.collectionView.mj_footer = [TopPullRefreshAnaimation footerWithRefreshingTarget:self refreshingAction:@selector(likeGetGoodsListsLoadMoreData)];
    
}

- (void)likeGetGoodsListsLoadMoreData
{
    refreshIndex ++;
    [self likeGetGoodsListsRequestData];
    [self.collectionView.mj_footer endRefreshing];
}

#pragma mark - 猜你喜欢数据
- (void)likeGetGoodsListsRequestData
{
    if (refreshIndex == 1) {
        [self.goodsListArray removeAllObjects];
    }
    NSString *P = [NSString stringWithFormat:@"%ld",refreshIndex];
    NSDictionary *params = @{@"p":[NSString stringWithFormat:@"%@",P],
                             @"recommend":@"5"
                             };
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/goods/appGoodLists" completeBlock:^(id object) {
            
            //刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (JudgeBackDataCode) {
                    
                    NSDictionary *tempDict = object[@"data"];
                    NSArray *arr = [tempDict objectForKey:@"list"];
                    _urlDict = tempDict[@"picprex"];
                    
                    for (NSDictionary *dict in arr) {
                        GoodListsModel *goodListsModel = [[GoodListsModel alloc] initWithDictionary:dict error:nil];
                        if (goodListsModel) {
                            [self.goodsListArray addObject:goodListsModel];
                            
                        }
                    }
                    
                }else{
                    
                    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                }
                //菊花隐藏
                [progressHUD hide:YES];
                [progressHUD removeFromSuperViewOnHide];
                [self.collectionView reloadData];
                
            });
            
        }];
        
    });
}

#pragma mark 购物车数据请求
- (void)reloadShopCarData {
    _pageIndex = 1;
    [self.shopCarTableView removeFromSuperview];
    [self.allProductArray removeAllObjects];
    _judgeLastView = YES;
    boola = YES;
    selectAll.selected = NO;
    priceLabel.text = [NSString stringWithFormat:@"￥0.0"];
    [self hideHud];
    [self showHudInView:self.view hint:@"正在加载中"];
    [self shopCartDatasources];
}

- (void)loadMoreSellRecode {
    _pageIndex++;
    [self shopCartDatasources];
    [self.shopCarTableView.mj_footer endRefreshing];
}

- (void)shopCartDatasources {
       if (!USERNAME) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您尚未登录用户" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *SettingAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LogInViewController *accountVC = [[LogInViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:accountVC];
            [self presentViewController:nav animated:YES completion:nil];
        }];
        [alert addAction:SettingAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self addMainCollectionView];
            [self likeGetGoodsListsRequestData];
            
        }];
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    
    [self.selectGoods removeAllObjects];
    NSDictionary *params = @{
                             @"username":USERNAME,
                             @"page":[NSString stringWithFormat:@"%ld",_pageIndex]
                             };
    NSLog(@"%ld",_pageIndex);
    NSString *string = @"/api/Cart/lists";

    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:string completeBlock:^(id object) {
        [self hideHud];
        if (!JudgeBackDataCode) {
            [self likeGetGoodsListsRequestData];
            [self addMainCollectionView];
            
            return;
        }
        
        NSMutableDictionary *dict = object[@"data"];
        _allProductCount = [dict objectForKey:@"count"];
        NSMutableArray *arrayM = dict[@"list"];
        NSLog(@"%ld",arrayM.count);
        if ((arrayM.count == 0) || (_pageIndex == 1 || arrayM.count < 4)) {
            [self.shopCarTableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        for (int i = 0; i < arrayM.count; i++) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            NSDictionary *dict1 = arrayM[i];
            [dict setObject:dict1[@"shopping_user"] forKey:@"shopping_user"];
            [dict setObject:dict1[@"shopping_data"] forKey:@"shopping_data"];
            NSNumber *number = [NSNumber numberWithBool:NO];
            [dict setObject:number forKey:@"isSellerSelected"];
            [dict setObject:number forKey:@"isEditOrNot"];
            Product *product = [[Product alloc] initWithDictionary:dict error:nil];
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSMutableDictionary *proInfo in product.shopping_data) {
                ProductInfo *productInfo = [ProductInfo newsWithDict:proInfo];
                productInfo.is_selected = NO;
                productInfo.is_editOrNot = NO;
                [tempArray addObject:productInfo];
            }
            [product setValue:tempArray forKey:@"shopping_data"];
            
            [self.allProductArray addObject:product];
        }
        
        [self.shopCarTableView.mj_header endRefreshing];
        
        
        if (self.allProductArray.count && _judgeLastView) {
            _judgeLastView = NO;
            
            [self addShopCarTableView];
        }
        
        [self.shopCarTableView reloadData];
    }];
}

#pragma mark 删除商品数据请求
- (void)deleteDatasources:(NSString *)replaceID andIndexPath:(NSIndexPath *)indexPath {
    
    [progressHUD hide:YES];
    
    NSDictionary *params = @{
                             @"username":USERNAME,
                             @"cart_id":replaceID
                             };
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NetWorkSharedTools sharedNetWorkTools] GetObjectWithURLDict:params AndMenthodName:@"/api/Cart/deleteById" completeBlock:^(id object) {
            NSLog(@"%@",object);
            
            NSDictionary *message = [object objectForKey:@"message"];
            dispatch_async(dispatch_get_main_queue(), ^{
                MBProgressHUD *hud = [MBProgressHUD showMessage:[message objectForKey:@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self countPrice];
                [self.view addSubview:hud];
            });
            
            
            if ([[NSString stringWithFormat:@"%@",object[@"code"]] isEqual:@"1"]) {
                
                for (int i = 0; i < self.selectGoods.count; i++) {
                    ProductInfo *model = self.selectGoods[i];
                    if ([[NSString stringWithFormat:@"%@",model.id] isEqualToString:replaceID]) {
                        [self.selectGoods removeObjectAtIndex:i];
                    } else {
                        break;
                    }
                }
                
                Product *model = self.allProductArray[indexPath.section];
                
                [model.shopping_data removeObjectAtIndex:indexPath.row];
                model.isEditOrNot = NO;
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:indexPath.section];
                [self.shopCarTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
                if (!model.shopping_data.count) {
                 
                    [self.allProductArray removeObjectAtIndex:indexPath.section];
                    [self.shopCarTableView reloadData];
                    
                }
//                [self.shopCarTableView reloadData];
            }
            
            
        }];
    });
}

- (void)SetUpShopCarEditNumber:(NSDictionary *)params {
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Cart/editNum" completeBlock:^(id object) {
        NSLog(@"%@",object);
    }];
}

#pragma mark - 添加控件
- (void)addShopCarTableView {
    
    isSelect = NO;
    
    CGFloat Navheight = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    
    CGFloat tabBarHeigjt = CGRectGetHeight(self.tabBarController.tabBar.frame);
    
    CGFloat tableViewHeight = HEIGHT - Navheight - tabBarHeigjt-49;
    if (_isPushCar) {
        tableViewHeight = HEIGHT - Navheight - tabBarHeigjt;
    }
    self.shopCarTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0 , WIDTH, tableViewHeight) style:UITableViewStylePlain];
    self.shopCarTableView.tableFooterView = [[UIView alloc] init];
    self.shopCarTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.shopCarTableView.delegate = self;
    self.shopCarTableView.dataSource = self;
    self.shopCarTableView.backgroundColor = RGB(234, 234, 234);
    self.shopCarTableView.mj_header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadShopCarData)];
    if (boola) {
        boola = NO;
         self.shopCarTableView.mj_footer = [TopPullRefreshAnaimation footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreSellRecode)];
    }
    
    [self.view addSubview:self.shopCarTableView];
    
    if (_judgeOnceAdd) {
        _judgeOnceAdd = NO;
        ShopCarLastView *lastView = [[ShopCarLastView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.shopCarTableView.frame), WIDTH, 49)];
        //    lastView.backgroundColor = [UIColor grayColor];
        selectAll = lastView.chooseButton;
        selectAll.selected = NO;
        [selectAll addTarget:self action:@selector(didClickChooseSelectedAllButton:) forControlEvents:UIControlEventTouchUpInside];
        
        priceLabel = lastView.priceLabel;
        priceLabel.text = [NSString stringWithFormat:@"￥0.0"];
        self.lastView = lastView;
        
        [lastView.accountButton addTarget:self action:@selector(didClickGoPayBttton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:lastView];
    }
}

- (void)addMainCollectionView
{
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    
    flowlayout.minimumLineSpacing = 2;
    flowlayout.minimumInteritemSpacing = 0;
    flowlayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    CGFloat height = CGRectGetMaxY(self.navigationController.navigationBar.frame);
    
    CGFloat tabBarHeight = CGRectGetHeight(self.tabBarController.tabBar.frame);
    if (_isPushCar) {
        tabBarHeight = 0;
    }
    UICollectionView *homeCollectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,0,WIDTH, HEIGHT-height-tabBarHeight) collectionViewLayout:flowlayout];
    self.collectionView = homeCollectView;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = BACKGROUND_COLOR;
    [self.view addSubview:_collectionView];
    
    //注册cell
    [self.collectionView registerClass:[homeCollectionViewCell class] forCellWithReuseIdentifier:CarlikeReuseIdentifier];
    
    //    注册表头
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"shopCarHeader"];
    
    refreshIndex = 1;
    [self addPullUpdateData];
}

#pragma mark - 计算价格逻辑和全选逻辑
-(void)countPrice
{
    double totlePrice = 0.0;
    
    [self.selectGoods removeAllObjects];
    [self.allProductArray enumerateObjectsUsingBlock:^(Product *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj.shopping_data enumerateObjectsUsingBlock:^(ProductInfo *info, NSUInteger idx, BOOL * _Nonnull stop) {
            if (info.is_selected) {
                [self.selectGoods addObject:info];
            }
        }];
        
    }];
    
    for (ProductInfo *model in self.selectGoods) {
        
        double price = [model.jiage doubleValue];
        
        totlePrice += price * model.nums;
    }
    priceLabel.text = [NSString stringWithFormat:@"￥%.1f",totlePrice];
    
    _totlePrice = totlePrice;
}


#pragma mark - 商铺按钮
- (void)didClickShopCarHeaderViewButton:(UIButton *)headerButton {
    
    Product *pro = self.allProductArray[headerButton.tag];
    NSArray *array = pro.shopping_data;
    if (headerButton.selected) {
        pro.isSellerSelected = YES;
        [array enumerateObjectsUsingBlock:^(ProductInfo *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.is_selected = YES;
            [self.selectGoods addObject:obj];
        }];
    } else {
        pro.isSellerSelected = NO;
        [array enumerateObjectsUsingBlock:^(ProductInfo *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.is_selected = NO;
            [self.selectGoods removeObject:obj];
        }];
    }
    
    __block NSInteger count = 0;
    [self.allProductArray enumerateObjectsUsingBlock:^(Product *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSellerSelected) {
            count++;
        }
    }];
    
    if (count == self.allProductArray.count) {
        selectAll.selected = YES;
    } else {
        selectAll.selected = NO;
    }
    
    [self.shopCarTableView reloadData];
    [self countPrice];
}


#pragma mark 商铺点击
- (void)didClickShopCarHeaderView {
    NSLog(@"%s",__func__);
}

#pragma mark 编辑按钮
- (void)didClickShopCarHeaderViewRightButton:(UIButton *)rightButton {
    Product *infoModel = self.allProductArray[rightButton.tag];
    infoModel.isEditOrNot = !infoModel.isEditOrNot;
    [self.shopCarTableView reloadData];
    
    if (!infoModel.isEditOrNot) {
        Product *model = self.allProductArray[rightButton.tag];
        for (ProductInfo *productInfo in model.shopping_data) {
            NSDictionary *params = @{
                                     @"username":USERNAME,
                                     @"cart_id":productInfo.id,
                                     @"num":[NSString stringWithFormat:@"%ld",productInfo.nums]
                                     };
            [self SetUpShopCarEditNumber:params];
        }
    }
}

#pragma mark 全选
- (void)didClickChooseSelectedAllButton:(UIButton *)selectedButton {
    //点击全选时,把之前已选择的全部删除
    [self.selectGoods removeAllObjects];
    
    //    selectedButton.selected = !selectedButton.selected;
    isSelect = selectedButton.selected;
    if (isSelect) {
        
        [self.allProductArray enumerateObjectsUsingBlock:^(Product *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSellerSelected = YES;
            [obj.shopping_data enumerateObjectsUsingBlock:^(ProductInfo *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.is_selected = YES;
                [self.selectGoods addObject:obj];
            }];
        }];
        
    } else {
        
        [self.allProductArray enumerateObjectsUsingBlock:^(Product *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSellerSelected = NO;
            [obj.shopping_data enumerateObjectsUsingBlock:^(ProductInfo *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                obj.is_selected = NO;
            }];
            
        }];
        
        [self.selectGoods removeAllObjects];
    }
    
    [self.shopCarTableView reloadData];
    [self countPrice];
}

#pragma mark 结算按钮
- (void)didClickGoPayBttton:(UIButton *)accountButton {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [self.selectGoods removeAllObjects];
        [self.allProductArray enumerateObjectsUsingBlock:^(Product *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            [obj.shopping_data enumerateObjectsUsingBlock:^(ProductInfo *info, NSUInteger idx, BOOL * _Nonnull stop) {
                if (info.is_selected) {
                    [self.selectGoods addObject:info];
                    NSLog(@"%@ - %@",info.title,info.id);
                }
            }];
            
        }];
        
        if (!self.selectGoods.count) {
            dispatch_async(dispatch_get_main_queue(), ^{
                MBProgressHUD *hud = [MBProgressHUD showMessage:@"请选择商品" toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self.view addSubview:hud];
            });
        } else {
            
            NSMutableArray *tmpArray = [NSMutableArray array];
            
            for (ProductInfo *model in self.selectGoods) {
                [tmpArray addObject:model.limit_buy];
            }
            
            static NSString *judgeType;
            
            for (int i = 0; i < tmpArray.count; i++) {
                
                NSString *string = [NSString stringWithFormat:@"%@",tmpArray[i]];
                
                if ([string isEqualToString:@"1"]) {
                    
                    for (ProductInfo *model in self.selectGoods) {
                        NSString *string = [NSString stringWithFormat:@"%@",model.limit_buy];
                        
                        if ([string isEqualToString:@"2"]) {
                            
                            dispatch_async(dispatch_get_main_queue(), ^{
                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"不同类型商品不可一起支付" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                
                                [alert show];
                            });
                            return ;
                        }
                    }
                }
            }
            
            for (ProductInfo *model in self.selectGoods) {
                NSString *string = [NSString stringWithFormat:@"%@",model.limit_buy];
                
                if ([string isEqualToString:@"1"]) {
                    judgeType = @"1";
                    break;
                } else {
                    judgeType = @"";
                }
            }
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showHudInView:self.view hint:@"正在创建订单"];
            });
            
            NSMutableArray *cartArray = [NSMutableArray array];
            for (ProductInfo *product in self.selectGoods) {
                [cartArray addObject:product.pid];
            }
            NSString *cartString = [cartArray componentsJoinedByString:@","];
            
            [[NetWorkSharedTools sharedNetWorkTools] GetObjectWithURLDict:@{@"products_id":cartString} AndMenthodName:@"/api/cart/checkOrder" completeBlock:^(id object) {
                NSLog(@"%@",object);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self hideHud];
                    if (JudgeBackDataCode) {
                        CarConfirmOrderController *confirm = [[CarConfirmOrderController alloc] init];
                        if (judgeType.length) {
                            confirm.typeString = judgeType;
                        }
                        confirm.productArray = self.selectGoods;
                        confirm.allPrice = [NSString stringWithFormat:@"%f",_totlePrice];
                        [self.navigationController pushForm:self.navigationController pushToAndHidden:confirm];
                    } else {
                        NSDictionary *diction = [object objectForKey:@"message"];
                        [self showHint:diction[@"msg"]];
                    }
                });
            }];
        }
    });
}

#pragma mark 删除按钮

- (void)didClickDeleteButton:(UIButton *)deleteButton andTableViewCell:(ShopCarTableViewCell *)TableViewCell {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定删除该商品" preferredStyle:UIAlertControllerStyleAlert];
    
    __weak typeof(self) weakSelf = self;
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        NSIndexPath *indexPath = [weakSelf.shopCarTableView indexPathForCell:TableViewCell];
        NSLog(@"%ld,%ld",indexPath.section,indexPath.row);
        
        Product *product = self.allProductArray[indexPath.section];
        ProductInfo *model = product.shopping_data[indexPath.row];
        NSString *shopId = [NSString stringWithFormat:@"%@",model.id];
        
        [weakSelf deleteDatasources:shopId andIndexPath:indexPath];
    }];
    [alert addAction:deleteAction];
    
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - collectionViewDataSource
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (self.goodsListArray.count) {
        return self.goodsListArray.count;
    }else{
        return 0;
    }
    
}

- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    homeCollectionViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:CarlikeReuseIdentifier forIndexPath:indexPath];
    
    if (!self.goodsListArray.count) {
        return cell;
    }
    
    GoodListsModel *goodListsModel = self.goodsListArray[indexPath.item];
    
    NSString *string = [NSString stringWithFormat:@"%@%@",_urlDict[@"m"],goodListsModel.picurl];
    [cell.productImage sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"placeholder"]];
    cell.productImage.contentMode = UIViewContentModeScaleToFill;
    
    cell.productName.text = goodListsModel.title;
    cell.price.text = [NSString stringWithFormat:@"专享价: %@",goodListsModel.huiyuanjia];
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    GoodListsModel *goodListsModel = self.goodsListArray[indexPath.item];
    ShopDetailsController *detailsVC = [[ShopDetailsController alloc] init];
    detailsVC.goodsId = goodListsModel.replaceID;
    [self.navigationController pushForm:self.navigationController pushToAndHidden:detailsVC];
}

//header组头大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    //头部视图size
    return CGSizeMake(WIDTH,HEIGHT/3);
    
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    return CGSizeMake(WIDTH/2-2, HEIGHT/2.8);
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(1,1,1,1);
}


-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *reusableView;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) { //
        
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"shopCarHeader" forIndexPath:indexPath];
        shopCarHeaderView *headerView = [[shopCarHeaderView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/3)];
        headerView.backgroundColor = [UIColor whiteColor];
        headerView.delegate = self;
        [reusableView addSubview:headerView];
        return reusableView;
    }
    return  nil;
}

- (void)shopCarHeaderButtonDidClick:(UIButton *)button
{
    NSLog(@"%ld",button.tag);
    RecommendedController*recommendedVC = [[RecommendedController alloc] init];
    recommendedVC.title = @"精品推荐";
    [self.navigationController pushForm:self.navigationController pushToAndHidden:recommendedVC];
    
}

#pragma mark - TableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.allProductArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    Product *product = self.allProductArray[section];
    
    return product.shopping_data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [progressHUD hide:YES];
    [progressHUD removeFromSuperview];
    
    __block ShopCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    
    if (!cell) {
        cell = [[ShopCarTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.leftButton.tag = indexPath.row;
    leftButton = cell.leftButton;
    cell.delegate = self;
    
    cell.deleteButton.tag = indexPath.row;
    cell.isSelected = isSelect;
    
    Product *product = self.allProductArray[indexPath.section];
    NSMutableArray *productArray = [NSMutableArray arrayWithArray:product.shopping_data];
    //是否被选中
    if ([_selectGoods containsObject:[productArray objectAtIndex:indexPath.row]]) {
        cell.isSelected = YES;
    }
    
    ProductInfo *model = productArray[indexPath.row];
    cell.isSelected = model.is_selected;
    
    
    
    //选择回调
    cell.cartBlock = ^(BOOL isSelec){
        
        if (isSelec) {
            model.is_selected = YES;
            [_selectGoods addObject:[productArray objectAtIndex:indexPath.row]];
            NSLog(@"%ld,%ld",indexPath.section,indexPath.row);
        } else {
            model.is_selected = NO;
            [_selectGoods removeObject:[productArray objectAtIndex:indexPath.row]];
            NSLog(@"%ld,%ld",indexPath.section,indexPath.row);
        }
        NSInteger count = 0;
        for (Product *product in self.allProductArray) {
            count += product.shopping_data.count;
        }
        
        if (_selectGoods.count == count) {
            selectAll.selected = YES;
        } else {
            selectAll.selected = NO;
        }
        
        __block NSInteger number = 0;
        [productArray enumerateObjectsUsingBlock:^(ProductInfo *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (obj.is_selected)
            {
                number++;
            }
        }];
        if (number == productArray.count) {
            product.isSellerSelected = YES;
        } else {
            product.isSellerSelected = NO;
        }
        [self.shopCarTableView reloadData];
        [self countPrice];
    };
    
    __block ShopCarTableViewCell *weakCell = cell;
    cell.numAddBlock =^(){
        
        NSInteger count = [weakCell.numberLabel.text integerValue];
        count++;
        NSString *numStr = [NSString stringWithFormat:@"%ld",(long)count];
        
        ProductInfo *model = [productArray objectAtIndex:indexPath.row];
        
        weakCell.numberLabel.text = numStr;
        model.nums = count;
        
        
        [productArray replaceObjectAtIndex:indexPath.row withObject:model];
        if ([_selectGoods containsObject:model]) {
            [_selectGoods removeObject:model];
            [_selectGoods addObject:model];
            [self countPrice];
        }
    };
    
    cell.numCutBlock =^(){
        
        NSInteger count = [weakCell.numberLabel.text integerValue];
        count--;
        if(count <= 0){
            return ;
        }
        NSString *numStr = [NSString stringWithFormat:@"%ld",(long)count];
        
        ProductInfo *model = [productArray objectAtIndex:indexPath.row];
        
        weakCell.numberLabel.text = numStr;
        
        model.nums = count;
        [productArray replaceObjectAtIndex:indexPath.row withObject:model];
        
        //判断已选择数组里有无该对象,有就删除  重新添加
        if ([_selectGoods containsObject:model]) {
            [_selectGoods removeObject:model];
            [_selectGoods addObject:model];
            [self countPrice];
        }
    };
    
    [cell reloadDataWith:product.shopping_data[indexPath.row]];
    
    if (!product.isEditOrNot) {
        cell.normalView.hidden = NO;
        cell.cutBtn.hidden = YES;
        cell.numberLabel.hidden = YES;
        cell.addBtn.hidden = YES;
        cell.normalNumberLabel.hidden = NO;
        cell.deleteButton.hidden = YES;
    } else {
        cell.normalView.hidden = YES;
        cell.normalNumberLabel.hidden = YES;
        cell.addBtn.hidden = NO;
        cell.cutBtn.hidden = NO;
        cell.numberLabel.hidden = NO;
        cell.deleteButton.hidden = NO;
    }
    
    return cell;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    ShoperCarHeaderView *headerView = [[ShoperCarHeaderView alloc] initWithFrame:CGRectMake(0,0, WIDTH, 33)];
    headerView.delegate = self;
    headerView.backgroundColor = [UIColor whiteColor];
    Product *product = self.allProductArray[section];
    headerView.leftButton.tag = section;
    headerView.leftButton.selected = product.isSellerSelected;
    headerView.titleLabel.text = product.shopping_user;
    headerView.rightButton.tag = section;
    NSString *string = product.isEditOrNot ? @"完成":@"编辑";
    [headerView.rightButton setTitle:string forState:UIControlStateNormal];
    headerView.sectionIndex = section;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView == self.shopCarTableView)
        
    {
        CGFloat sectionHeaderHeight = 33; //sectionHeaderHeight
        
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
            
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
            
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    Product *model = self.allProductArray[indexPath.section];
    if (!model.isEditOrNot) {
        return 106;
    } else {
        return 94;
    }
    
}

#pragma mark - 懒加载
- (NSMutableArray *)productsArray {
    if (!_productsArray) {
        _productsArray = [NSMutableArray array];
    }
    return _productsArray;
}

- (NSMutableArray *)selectedButton {
    if (!_selectedButton) {
        _selectedButton = [NSMutableArray array];
    }
    return _selectedButton;
}

- (NSMutableArray *)selectGoods {
    if (!_selectGoods) {
        _selectGoods = [NSMutableArray array];
    }
    return _selectGoods;
}


- (NSMutableArray *)goodsListArray {
    if (!_goodsListArray) {
        _goodsListArray = [NSMutableArray array];
    }
    return _goodsListArray;
}

- (NSMutableArray *)allProductArray {
    if (!_allProductArray) {
        _allProductArray = [NSMutableArray array];
    }
    return _allProductArray;
}

- (NSMutableDictionary *)SellerLeftButtonDiction {
    if (!_SellerLeftButtonDiction) {
        _SellerLeftButtonDiction = [NSMutableDictionary dictionary];
    }
    return _SellerLeftButtonDiction;
}
@end
